package com.touchalachs.game;

import com.touchalachs.core.TimeUtil;
import com.touchalachs.core.Updatable;

public class Calculator implements Updatable{


	private volatile double score;
	private volatile double income;
	private volatile int spent;
	private volatile int startTime;
	private final int[] workerCount;

	public Calculator(String saveString){
		workerCount = new int[]{0, 0, 0, 0};
		if (saveString.isEmpty()){
			restart();
		}else{
			load(saveString);
		}
	}

	public void restart() {
		score = 0;
		income = 0;
		spent = 0;
		startTime = TimeUtil.getTime();
		for (int i=0; i<workerCount.length; i++){
			workerCount[i] = 0;
		}
	}

	public void clickFish(){
		score += Balancing.SCORE_PER_FISH_CLICK;
	}
	
	public int getScore(){
		return (int)score;
	}
	
	public double getIncome(){
		return income;
	}
	
	public int getDuration(){
		return TimeUtil.getTime() - startTime;
	}
	
	public int getAllTimeScore(){
		return (int)score + spent;
	}
	
	public boolean buyWorker(int index){
		if (index>=0 && index<workerCount.length){
			int cost = Balancing.getCost(index, workerCount[index]);
			if (score >= cost){
				workerCount[index]++;
				income += Balancing.getIncome(index);
				score -= cost;
				spent += cost;
				return true;
			}
		}
		return false;
	}
	
	public int getWorkerCount(int index){
		if (index>=0 && index<workerCount.length){
			return workerCount[index];
		}else{
			return -1;
		}
	}

	@Override
	public void update(float deltaSec) {
		score += income*deltaSec;
	}

	public String getSaveString() {
		String save = "";
		for(int i=0; i<workerCount.length; i++){
			save += workerCount[i]+"+";
		}
		return ""+score+"#"+spent+"#"+getDuration()+"#"+save;
	}
	
	private void load(String saveString) {
		String[] a = saveString.split("#");
		score = Double.parseDouble(a[0]);
		spent = Integer.parseInt(a[1]);
		startTime = TimeUtil.getTime() - Integer.parseInt(a[2]);
		income = 0;
		String[] w = a[3].split("[+]");
		for(int i=0; i<w.length; i++){
			workerCount[i] = Integer.parseInt(w[i]);
			income += workerCount[i] * Balancing.getIncome(i);
		}
	}
}
